<template>
  <div>
    <table-search
      ref="tableSearch"
      title="报备记录"
      :columns="columns"
      :api="getList"
      :tabs-options="tabsOptions"
    >
      <template #bidEndTime="{ row }">
        {{row.bidEndTime | dateFilterToDay}}
      </template>
      <template #createTime="{ row }">
        {{row.createTime | dateFilter}}
      </template>
      <template #goodSkuNum="{ row }">{{row.goodSkuNum || 0}}条</template>
      <template #goodTotalPrice="{ row }">{{row.goodTotalPrice}}元</template>
      <template #status="{ row }">
        <div class="hasEdit" v-if="row.isUpdate==0">
          <span class="text">改</span>
        </div>
        <p :class="{'red':row.filingState==1,'orange':row.filingState==2,'grey':row.filingState>4}">{{ row.filingState | statusListC1_b}}</p>
        <el-button @click.native.prevent="showAuditRecord(row.id)" type="text" size="small">
          审核记录
          <i class="el-icon-arrow-right"></i>
        </el-button>
      </template>

      <template #operate="{ row }">
        <div>
          <router-link :to="`/customer/bidding/detail?id=${row.id}`" target="_blank">
            <el-button type="text" size="small">查看详情</el-button>
          </router-link>

          <el-button style="margin-left: 10px;" disabled v-if="row.filingState > 2" type="text" size="small">修改信息</el-button>
          <router-link v-else :to="`/customer/bidding/detail?id=${row.id}&type=1`">
            <el-button style="margin-left: 10px;" type="text" size="small">修改信息</el-button>
          </router-link>
        </div>
        <div>
          <el-button type="text" size="small" @click="onCopyReport(row)">再次报备</el-button>
          <el-popconfirm title="确认要取消此次竞价报备吗？" @onConfirm="onCancel(row)">
            <el-button style="margin-left: 10px;" slot="reference" :disabled="row.filingState > 2" type="text" size="small">取消报备</el-button>
          </el-popconfirm>
        </div>
      </template>
    </table-search>

    <el-dialog title="审核记录" :visible.sync="auditRecordState.show" width="60%">
      <el-table
        v-loading="auditRecordState.loading"
        :data="auditRecordState.data"
        border
        :header-cell-style="{ backgroundColor: '#f5f5f5', color: '#333', fontWeight: 'bold', textAlign:'center' }"
        max-height="500"
      >
        <el-table-column align="center" label="时间" width="200">
          <template slot-scope="scope">{{scope.row.operatorTime | dateFilter}}</template>
        </el-table-column>
        <el-table-column property="operator" label="操作人" width="150" align="center"></el-table-column>
        <el-table-column label="审核状态" width="100" align="center">
          <template slot-scope="scope">{{scope.row.auditStatus | statusFilterC2_b}}</template>
        </el-table-column>
        <el-table-column label="详情">
          <template slot-scope="scope">
            <el-row v-for="(item,index) in scope.row.auditDetail" :key="index">{{item.auditDetail}}</el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog v-loading="associatedInfoState.loading" :title="`上架信息反馈 (订单号：${associatedInfoState.data.orderId || '-'})`" :visible.sync="associatedInfoState.show" width="60%">
      <el-table
        :data="associatedInfoState.data.items || []"
        border
        :header-cell-style="{ backgroundColor: '#f5f5f5', color: '#333', fontWeight: 'bold', textAlign:'center' }"
        max-height="500"
      >
        <el-table-column align="center" label="序号" width="150" type="index"></el-table-column>
        <el-table-column label="商品名称" prop="goodsName"></el-table-column>
        <el-table-column align="center" label="商品编码" prop="skuId"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, computed, reactive, getCurrentInstance } from '@vue/composition-api'
import TableSearch from '@/components/TableSearch/TableSearch'
import { createTableColumns } from '@/components/TableSearch/utils'
import { queryBidFilingAuditRecord, associatedInfo } from '@/api/myFiling'
import { queryBidFilingList, cancelBidFiling, filingInfo } from '@/api/bid'
import dict from '@/lib/dict'
import { useProjectSelectOption, useProjectCustomerSetting } from '@/hooks/project'
import { useReport } from '@/hooks/report'

const { statusListC1_b: DictOrderStatusList } = dict

export default defineComponent({
  components: {
    TableSearch,
  },
  setup () {
    const instance = getCurrentInstance()

    const projectSelectOption = useProjectSelectOption()

    const columns = computed(() => {
      return createTableColumns([
        ['报备编号', 'filingNumber', { search: true }],
        ['提交时间', 'createTime', { search: { sort: 9, key: ['commitStartTime', 'commitEndTime'] } }],
        ['项目名称', 'bidPlatformName', { search: { key: 'bidPlatformId', type: 'select', options: projectSelectOption.value } }],
        ['项目编号', 'projectId', { search: true }],
        ['竞价截止时间', 'bidEndTime'],
        ['商品条数', 'goodSkuNum'],
        ['商品总价', 'goodTotalPrice'],
        ['备注', 'remark'],
        ['报备状态', 'status'],
        ['操作', 'operate'],
      ])
    })

    console.log('DictOrderStatusList', DictOrderStatusList)
    const tabsOptions = reactive({
      list: [{ code: 'all', desc: '全部报备' }, ...DictOrderStatusList],
      data: {},
      searchKey: 'filingState',
    })

    const getList = async (index, size, query) => {
      const result = await queryBidFilingList(index, size, query)
      initDataCount(result.bidBaseInfoCount)
      return result.filingBidBaseInfoPageResult
    }

    const initDataCount = async (result) => {
      const dataKeyMap = {
        1: 'waitAuditing',
        2: 'waitBid',
        3: 'onBid',
        4: 'bidSuccess',
        5: 'bidFailed',
        6: 'reviewFailed',
        7: 'providerCancel',
        all: 'totalCount',
      }
      const data = {}
      tabsOptions.list.forEach(item => {
        data[item.code] = result[dataKeyMap[item.code]]
      })
      tabsOptions.data = data
    }

    // 审核记录
    const auditRecordState = reactive({
      show: false,
      loading: false,
      id: null,
      data: [],
    })
    const showAuditRecord = async id => {
      auditRecordState.show = true
      if (id !== auditRecordState.id) {
        auditRecordState.id = id
        auditRecordState.loading = true
        const result = await queryBidFilingAuditRecord(id)
        console.log('result', result)
        auditRecordState.data = result.map(item => {
          item.auditDetail = JSON.parse(item.auditDetail)
          return item
        })
        auditRecordState.loading = false
      }
    }

    // 上架信息反馈
    const associatedInfoState = reactive({
      show: false,
      loading: false,
      id: null,
      data: {},
    })
    const showAssociatedInfo = async item => {
      associatedInfoState.show = true
      if (associatedInfoState.id !== item.id) {
        associatedInfoState.id = item.id
        associatedInfoState.loading = true
        associatedInfoState.data = await associatedInfo(item.id, item.status)
        associatedInfoState.loading = false
      }
    }

    const onCancel = async (item) => {
      const loading = instance.$loading()
      try {
        const message = await cancelBidFiling(item.id)
        instance.$message({
          type: 'success',
          message,
        })
        instance.$refs.tableSearch.reload()
      } catch (error) { }
      loading.close()
    }

    const { setProjectId } = useProjectCustomerSetting()
    const { reportState, reportReset, gotoReport } = useReport()
    const onCopyReport = async (item) => {
      const result = await filingInfo(item.id)
      reportReset()
      setProjectId(result.bidPlatformId, false)
      reportState.type = 'biding'
      reportState.form = result
      reportState.step = 1
      gotoReport(false)
    }

    return {
      columns,
      getList,
      tabsOptions,
      auditRecordState,
      showAuditRecord,
      associatedInfoState,
      showAssociatedInfo,
      onCancel,
      onCopyReport,
    }
  },
})
</script>

<style lang="scss" scoped>
.grey {
  color: #bbb;
}
.red {
  color: red;
}
.hasEdit {
  position: absolute;
  top: 0;
  left: 0;
  &::before {
    content: '';
    display: block;
    width: 0;
    height: 0;
    border-top: 30px solid red;
    border-right: 30px solid transparent;
  }
  .text {
    position: absolute;
    top: -3px;
    left: 2px;
    color: #fff;
    font-size: 12px;
  }
}
</style>
